package cn.com.baozun.sany.websocket;

import cn.com.baozun.sany.workbench.application.publisher.OnlineChangePublisher;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @title: WebSocketHandler
 * @description:
 * @author: guan.xin
 * @create: 2021-05-25 17:02
 * @since: JDK8
 */
@Component
public class WebSocketHandler extends TextWebSocketHandler {

    private static final Map<Long, WebSocketSession> sessions = new HashMap<>();

    @Resource
    private MessageSendService messageSendService;

    @Resource
    private OnlineChangePublisher onlineChangePublisher;

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        System.out.println("获取到消息 >> " + message.getPayload());

        if (session.isOpen()) {
            session.sendMessage(new TextMessage("消息已收到"));

            onlineChangePublisher.sendMessage();
        }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String uid = (String) session.getAttributes().get("uid");
        session.sendMessage(new TextMessage(uid + ", 你好！欢迎连接到ws服务"));

//        if (session.isOpen()) {
//            messageSendService.setSession(session);
//            try {
//                messageSendService.send();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("断开连接！");
    }
}
